package com.example.common.livedata

import android.util.Log
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * LiveData数据倒灌问题
 * */
open class SingleLiveEvent<T> : MutableLiveData<T>(){

    private val mPending = AtomicBoolean(false)

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
       if (hasActiveObservers()){
           Log.w("SingleLiveEvent","Multiple observers registered but only one will be notified of changes.")
       }

        //观察MutableLiveData数据
        super.observe(owner, Observer { t ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(t: T?) {
        mPending.set(true)
        super.setValue(t)
    }
    /**
     * 用于T为Void的情况，使调用更简洁
     * */
    @MainThread
    fun call(){
        value= null
    }

    /**
     * 用作通过表示事件的LiveData公开的数据的包装器
     * */
    open class Event<out T>(private val content: T) {
        var hasBeenHandled = false
            private set // Allow external read but not write

        /**
         * 返回内容并防止再次使用
         */
        fun getContentIfNotHandled(): T? {
            return if (hasBeenHandled) {
                null
            } else {
                hasBeenHandled = true
                content
            }
        }

        /**
         * 返回内容即使它已经被处理过
         */
        fun peekContent(): T = content
    }

    /**
     *简化Event的内容是否已经被处理
     *
     * 如果未被处理时调用
     */
    class EventObserver<T>(private val onEventUnhandledContent : (T)->Unit) : Observer<Event<T>>{
        override fun onChanged(value: Event<T>) {
            value.getContentIfNotHandled()?.let {
                onEventUnhandledContent(it)
            }
        }
    }



}